package repository

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/service/promotion/model"

	"github.com/sirupsen/logrus"
	"github.com/volatiletech/null/v8"
	"github.com/volatiletech/sqlboiler/v4/boil"
	"github.com/volatiletech/sqlboiler/v4/queries/qm"
	"github.com/zeromicro/go-zero/core/stores/cache"
)

type (
	// CouponRepository is an interface to be customized, add more methods here,
	// and implement the added methods in customCouponRepository.
	CouponRepository interface {
		FindOne(ctx context.Context, id uint64) (*model.PromotionCoupon, error)
		FindOneWithExpire(
			ctx context.Context,
			id uint64,
			expire time.Duration,
		) (*model.PromotionCoupon, error)
		FindOneNoCache(
			ctx context.Context,
			conn boil.ContextExecutor,
			id uint64,
		) (*model.PromotionCoupon, error)
		GetList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.PromotionCoupon, int64, error) // ##25.03.17##
		Insert(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.PromotionCoupon,
		) error
		Update(
			ctx context.Context,
			tx boil.ContextExecutor,
			data *model.PromotionCoupon,
		) error
		UpdateBatch(ctx context.Context, tx boil.ContextExecutor, ids []uint64, cols model.M) error
		SoftDelete(ctx context.Context, tx boil.ContextExecutor, id uint64) error
		Restore(ctx context.Context, tx boil.ContextExecutor, id uint64) error
		ForceDelete(ctx context.Context, tx boil.ContextExecutor, id uint64) error
		ForceDeleteBatch(ctx context.Context, tx boil.ContextExecutor, ids []uint64) error
	}

	customCouponRepository struct {
		modelx.CachedConn
		mysqlConn           *sql.DB
		cacheIdPrefix       string
		cacheIdExpirePrefix string
	}
)

// NewCouponRepository returns a repository for the database table.
func NewCouponRepository(mysqlConn *sql.DB, cacheConf cache.CacheConf) CouponRepository {
	return &customCouponRepository{
		CachedConn:          modelx.NewConn(mysqlConn, cacheConf),
		mysqlConn:           mysqlConn,
		cacheIdPrefix:       "cache:promotion:user_coupons:id:",
		cacheIdExpirePrefix: "cache:promotion:user_coupons:id:expire:",
	}
}

func (r *customCouponRepository) FindOne(
	ctx context.Context,
	id uint64,
) (*model.PromotionCoupon, error) {
	cacheIdKey := r.formatPrimary(id)
	var resp model.PromotionCoupon
	err := r.QueryCtx(ctx, &resp, cacheIdKey, func(ctx context.Context, conn *sql.DB, v any) error {
		data, err := model.FindPromotionCoupon(ctx, conn, id)
		if err != nil {
			return err
		}

		*v.(*model.PromotionCoupon) = *data

		return nil
	})

	switch err {
	case nil:
		return &resp, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customCouponRepository) FindOneWithExpire(
	ctx context.Context,
	id uint64,
	expire time.Duration,
) (*model.PromotionCoupon, error) {
	cacheIdKey := r.formatPrimary(id)
	var resp model.PromotionCoupon
	err := r.QueryWithExpireCtx(ctx, &resp, cacheIdKey, expire, func(ctx context.Context, conn *sql.DB, v any) error {
		data, err := model.FindPromotionCoupon(ctx, conn, id)
		if err != nil {
			return err
		}

		*v.(*model.PromotionCoupon) = *data

		return nil
	})

	switch err {
	case nil:
		return &resp, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customCouponRepository) FindOneNoCache(
	ctx context.Context,
	conn boil.ContextExecutor,
	id uint64,
) (*model.PromotionCoupon, error) {
	var db boil.ContextExecutor = r.mysqlConn
	if conn != nil {
		db = conn
	}
	data, err := model.FindPromotionCoupon(ctx, db, id)
	logrus.Info(fmt.Sprintf("FindOneNoCache err: %+v", err))
	switch err {
	case nil:
		return data, nil
	case sql.ErrNoRows:
		return nil, model.ErrNotFound
	default:
		return nil, err
	}
}

func (r *customCouponRepository) GetList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.PromotionCoupon, count int64, err error) {
	var page int
	var pageSize int
	var limit int
	var selectCol string
	var mods []qm.QueryMod
	var nextCount int64
	var previousCount int64
	var statistic bool
	var oldest bool
	var latest bool
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(uint64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(uint64); ok && val > 0 {
				pageSize = int(val)
			}
		case "limit":
			if val, ok := v.(uint32); ok && val > 0 {
				limit = int(val)
			}
		case "offset":
			if withCount == 2 {
				if val, ok := v.(uint32); ok && val > 0 {
					mods = append(mods, qm.Offset(int(val)))
					previousCount = 1
				}
			}
		case "orderBy":
			if val, ok := v.(string); ok && len(val) > 0 {
				mods = append(mods, qm.OrderBy(val))
			}
		case "preMinId":
			if withCount == 3 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.PromotionCouponColumns.CouponID+" DESC"))
					mods = append(mods, model.PromotionCouponWhere.CouponID.LT(val))
					previousCount = 1
				}
			}
		case "preMaxId":
			if withCount == 4 {
				if val, ok := v.(uint64); ok && val > 0 {
					mods = append(mods, qm.OrderBy(model.PromotionCouponColumns.CouponID+" ASC"))
					mods = append(mods, model.PromotionCouponWhere.CouponID.GT(val))
					previousCount = 1
				}
			}
		case "select":
			if withCount != 5 {
				if val, ok := v.(string); ok && len(val) > 0 {
					selectCol = val
				}
			}
		case "statistic":
			if val, ok := v.(string); ok && val == "1" { // 按 Status 统计
				statistic = true
			}
		case "oldest":
			if val, ok := v.(string); ok && val == "1" {
				oldest = true
			}
		case "latest":
			if val, ok := v.(string); ok && val == "1" {
				latest = true
			}
		}
	}

	for key, opMap := range filter {
		switch key {
		case model.PromotionCouponColumns.CouponID:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponColumns.CouponID, opMap)...)
		case model.PromotionCouponColumns.ActivityID:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponColumns.ActivityID, opMap)...)
		case model.PromotionCouponColumns.TemplateID:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponColumns.TemplateID, opMap)...)
		case model.PromotionCouponColumns.SourceType:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponColumns.SourceType, opMap)...)
		case model.PromotionCouponColumns.CouponCode:
			mods = append(mods, modelx.GetStringMods(model.PromotionCouponColumns.CouponCode, opMap)...)
		case model.PromotionCouponColumns.UserID:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponColumns.UserID, opMap)...)
		case model.PromotionCouponColumns.OrderID:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponColumns.OrderID, opMap)...)
		case model.PromotionCouponColumns.Status:
			mods = append(mods, modelx.GetIntMods(model.PromotionCouponColumns.Status, opMap)...)
		case model.PromotionCouponColumns.StartedAt:
			mods = append(mods, modelx.GetTimeMods(model.PromotionCouponColumns.StartedAt, opMap)...)
		case model.PromotionCouponColumns.EndedAt:
			mods = append(mods, modelx.GetTimeMods(model.PromotionCouponColumns.EndedAt, opMap)...)
		case model.PromotionCouponColumns.CreatedAt:
			mods = append(mods, modelx.GetTimeMods(model.PromotionCouponColumns.CreatedAt, opMap)...)
		case model.PromotionCouponColumns.UpdatedAt:
			mods = append(mods, modelx.GetTimeMods(model.PromotionCouponColumns.UpdatedAt, opMap)...)
		}
	}

	if statistic {
		mods = append(mods, qm.Select(fmt.Sprintf(
			"%s, count(%s) as %s",
			model.PromotionCouponColumns.Status,
			model.PromotionCouponColumns.Status,
			model.PromotionCouponColumns.OrderID,
		)))
		mods = append(mods, qm.GroupBy(model.PromotionCouponColumns.Status))
		preList, preErr := model.PromotionCoupons(mods...).All(ctx, r.mysqlConn)
		if preErr != nil {
			err = preErr
			return
		}

		return preList, 0, nil
	}

	if oldest || latest {
		if oldest {
			mods = append(mods, qm.Select(fmt.Sprintf(
				"min(%s) as %s",
				model.PromotionCouponColumns.CouponID,
				model.PromotionCouponColumns.CouponID,
			)))
		} else {
			mods = append(mods, qm.Select(fmt.Sprintf(
				"max(%s) as %s",
				model.PromotionCouponColumns.CouponID,
				model.PromotionCouponColumns.CouponID,
			)))
		}
		mods = append(mods, qm.GroupBy(model.PromotionCouponColumns.TemplateID))

		if withCount == 2 && limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}

		preList, listErr := model.PromotionCoupons(mods...).All(ctx, r.mysqlConn)
		if listErr != nil {
			err = listErr
			return
		}

		if len(preList) > 0 {
			if withCount >= 2 {
				if limit > 0 && len(preList) > limit {
					nextCount = 1
					preList = preList[:limit]
				}
				count = previousCount + nextCount*2
			}
			if len(preList) == 0 {
				return
			}

			cids := make([]uint64, 0, len(preList))
			for _, v := range preList {
				cids = append(cids, v.CouponID)
			}
			var subMods []qm.QueryMod
			subMods = append(subMods, model.PromotionCouponWhere.CouponID.IN(cids))
			var columns []string
			if len(selectCol) > 0 {
				if selectCol == "," {
					columns = append(columns, model.PromotionCouponColumns.CouponID)
				} else {
					columns = strings.Split(selectCol, ",")
				}
			}
			if len(columns) > 0 {
				subMods = append(subMods, qm.Select(columns...))
			}
			list, err = model.PromotionCoupons(subMods...).All(ctx, r.mysqlConn)
			return
		}

		return
	}

	if withCount >= 2 {
		if withCount == 5 { // 统计领取次数
			mods = append(mods, qm.Select(fmt.Sprintf(
				"%s, count(%s) as %s",
				model.PromotionCouponColumns.TemplateID,
				model.PromotionCouponColumns.TemplateID,
				model.PromotionCouponColumns.OrderID,
			)))
			mods = append(mods, qm.GroupBy(model.PromotionCouponColumns.TemplateID))
		}

		if limit > 0 {
			mods = append(mods, qm.Limit(limit+1))
		}
	} else if withCount >= 0 {
		count, err = model.PromotionCoupons(mods...).Count(ctx, r.mysqlConn)
		if err != nil {
			return
		}

		if withCount == 0 {
			return
		}
	}

	if pageSize > 0 && (withCount == -1 || withCount == 1) {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	}

	var columns []string
	if len(selectCol) > 0 {
		if selectCol == "," {
			columns = append(columns, model.PromotionCouponColumns.CouponID)
		} else {
			columns = strings.Split(selectCol, ",")
		}
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.PromotionCoupons(mods...).All(ctx, r.mysqlConn)
	if err != nil {
		return
	}

	if withCount >= 2 {
		if limit > 0 && len(list) > limit {
			nextCount = 1
			list = list[:limit]
		}
		count = previousCount + nextCount*2
	}

	return
}

func (r *customCouponRepository) Insert(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.PromotionCoupon,
) error {
	err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		err := data.Insert(ctx, db, boil.Infer())
		if err != nil {
			return err
		}

		// id := data.CouponID

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customCouponRepository) Update(
	ctx context.Context,
	tx boil.ContextExecutor,
	data *model.PromotionCoupon,
) error {
	err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Blacklist(
			model.PromotionCouponColumns.CouponID,
			model.PromotionCouponColumns.DeletedAt,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		// id := data.CouponID

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customCouponRepository) UpdateBatch(
	ctx context.Context,
	tx boil.ContextExecutor,
	ids []uint64,
	cols model.M,
) error {
	if len(ids) > 0 {
		err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
			var db boil.ContextExecutor
			if tx != nil {
				db = tx
			} else {
				db = conn
			}

			var mods []qm.QueryMod
			mods = append(mods, model.PromotionCouponWhere.CouponID.IN(ids))

			rowsAff, err := model.PromotionCoupons(mods...).UpdateAll(ctx, db, cols)
			if err != nil {
				return err
			}

			if rowsAff == 0 {
				return model.ErrNotUpdated
			}

			return nil
		}, r.formatPrimaries(ids)...)

		return err
	}

	return nil
}

func (r *customCouponRepository) SoftDelete(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	if data.Status == uint16(globalkey.StatusDeleted) {
		return nil
	}

	data.DelStatus = data.Status
	data.Status = uint16(globalkey.StatusDeleted)
	data.DeletedAt = null.TimeFrom(time.Now())

	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Blacklist(
			model.PromotionCouponColumns.CouponID,
			model.PromotionCouponColumns.UpdatedAt,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customCouponRepository) Restore(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	if data.Status != uint16(globalkey.StatusDeleted) {
		return nil
	}

	data.Status = data.DelStatus
	data.DeletedAt = null.TimeFromPtr(nil)

	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Update(ctx, db, boil.Blacklist(
			model.PromotionCouponColumns.CouponID,
			model.PromotionCouponColumns.UpdatedAt,
		))
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotUpdated
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customCouponRepository) ForceDelete(
	ctx context.Context,
	tx boil.ContextExecutor,
	id uint64,
) error {
	data, err := r.FindOneNoCache(ctx, tx, id)
	if err != nil {
		if err == model.ErrNotFound {
			return nil
		}

		return err
	}

	err = r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
		var db boil.ContextExecutor
		if tx != nil {
			db = tx
		} else {
			db = conn
		}

		rowsAff, err := data.Delete(ctx, db)
		if err != nil {
			return err
		}

		if rowsAff == 0 {
			return model.ErrNotDeleted
		}

		return nil
	}, r.getCacheKeys(data)...)

	return err
}

func (r *customCouponRepository) ForceDeleteBatch(
	ctx context.Context,
	tx boil.ContextExecutor,
	ids []uint64,
) error {
	if len(ids) > 0 {
		err := r.ExecCtx(ctx, func(ctx context.Context, conn *sql.DB) error {
			var db boil.ContextExecutor
			if tx != nil {
				db = tx
			} else {
				db = conn
			}

			var mods []qm.QueryMod
			mods = append(mods, model.PromotionCouponWhere.CouponID.IN(ids))

			rowsAff, err := model.PromotionCoupons(mods...).DeleteAll(ctx, db)
			if err != nil {
				return err
			}

			if rowsAff == 0 {
				return model.ErrNotDeleted
			}

			return nil
		}, r.formatPrimaries(ids)...)

		return err
	}

	return nil
}

func (r *customCouponRepository) getCacheKeys(data *model.PromotionCoupon) []string {
	if data == nil {
		return []string{}
	}

	cacheIdKey := r.formatPrimary(data.CouponID)
	cacheKeys := []string{
		cacheIdKey,
	}

	return cacheKeys
}

func (r *customCouponRepository) formatPrimary(primary any) string {
	return fmt.Sprintf("%s%v", r.cacheIdPrefix, primary)
}

func (r *customCouponRepository) formatPrimaries(primaries []uint64) []string {
	var resp []string
	for _, primary := range primaries {
		resp = append(resp, r.formatPrimary(primary))
	}

	return resp
}

func (r *customCouponRepository) queryPrimary(ctx context.Context, conn *sql.DB, v, primary any) error {
	var uid uint64
	if jsonId, ok := primary.(json.Number); ok {
		if int64Id, err := jsonId.Int64(); err == nil {
			uid = uint64(int64Id)
		} else {
			return err
		}
	}

	data, err := model.FindPromotionCoupon(ctx, conn, uid)
	if err != nil {
		return err
	}

	*v.(*model.PromotionCoupon) = *data

	return nil
}
